package com.jike.shop.cloud.mq;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jike.shop.cloud.constants.MQConstants;
import com.jike.shop.cloud.entity.Payment;
import com.jike.shop.cloud.mapper.PaymentMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "GID_payment_consumer", topic = MQConstants.TOPIC_PAYMENT)
public class PaymentMessageListener implements RocketMQListener<PaymentMessage> {

    @Autowired
    private PaymentMapper paymentMapper;

    @Autowired
    private MQProducer mqProducer;

    @Override
    public void onMessage(PaymentMessage message) {
        //todo 超时关闭订单，发送MQ通知
        if (message == null) {
            log.error("empty message");

            return;
        }

        log.info("received payment message: {}", message);
        if (message.getType() == PaymentMessage.TYPE_OUT_OF_TIME) {
            //todo 根据支付渠道拉取支付结果，判断是否需要关闭订单
            int rows = paymentMapper.update(new Payment(), Wrappers.lambdaUpdate(Payment.class)
                    .set(Payment::getStatus, Payment.STATE_CLOSED)
                    .eq(Payment::getId, message.getPaymentId())
                    .eq(Payment::getStatus, Payment.STATE_INIT)
            );
            if (rows != 1) {
                log.error("wrong payment status: {}", message.getPaymentId());

                return;
            }

            mqProducer.sendPaymentStatusChangedMessage(message.getPaymentId(), Payment.STATE_CLOSED);
        } else {
            log.warn("unknown message type: {}", message.getType());
        }
    }
}
